package vip.housir.kotlineleme

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.os.Build
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.webkit.*
import android.widget.EditText
import android.widget.Toast
import android.widget.Toast.makeText
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

	private val baseUrl = "file:///android_asset/index.html"
	private val kClass = "MainActivity"  //定义Log的TAG

	@RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_main)
		initWebView()
	}

	@RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
	@SuppressLint("SetJavaScriptEnabled", "AddJavascriptInterface")
	private fun initWebView() {
		// with语法糖，下面的每一句，都加上with（）括号里的内容为前缀，如下看注释
		with(webview!!.settings!!) {
			//webview!!.settings.javaScriptEnabled = true
			javaScriptEnabled = true
			javaScriptCanOpenWindowsAutomatically = true
			// 设置允许访问文件数据
			allowFileAccess = true
			//支持缩放
			setSupportZoom(true)
//			cacheMode = WebSettings.LOAD_NO_CACHE
			domStorageEnabled = true
			databaseEnabled = true
			allowUniversalAccessFromFileURLs = true
		}
		with(webview!!) {
			webViewClient = webClient
			webChromeClient = chromeClient
			loadUrl(baseUrl)
			addJavascriptInterface(object {
				@SuppressLint("ShowToast")
				@JavascriptInterface
				fun showToast(string: String) {
					val text = android.widget.Toast.makeText(this@MainActivity, string, android.widget.Toast.LENGTH_SHORT)
					text.show()
				}
			}, "JSTest")
		}
	}

	private val webClient = object : WebViewClient() {
		override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
			Log.d(kClass, request.toString())
			return true
		}
	}

	private val chromeClient = object : WebChromeClient() {
		override fun onJsAlert(view: WebView?, url: String?, message: String?, result: JsResult?): Boolean {
			with(AlertDialog.Builder(this@MainActivity)) {
				setTitle("Java成功重写了Js的Alert方法")
				setMessage("$message & $url")//这个message就是alert传递过来的值
				setPositiveButton("确定") { _, _ -> result?.confirm() }
				setOnCancelListener {
					//防止用户点击对话框外围，再次点击按钮页面无响应
					result?.cancel()
				}
				show()
			}
			//自己处理
			return true
		}

		@SuppressLint("ShowToast")
		override fun onJsPrompt(view: WebView?, url: String?, message: String?, defaultValue: String?, result: JsPromptResult?): Boolean {
			val editText = EditText(this@MainActivity)
			editText.setText(defaultValue)//这个就是prompt 输入框的默认值
			with(AlertDialog.Builder(this@MainActivity)) {
				setTitle("Java成功重写了Js的Prompt方法")
				setMessage(message)//这个message就是alert传递过来的值
				//添加一个EditText
				//添加到对话框
				setView(editText)
				setPositiveButton("确定") { _, _ ->
					//获取 edittext 的新输入的值
					val text = editText.text.toString()
					val makeText = makeText(this@MainActivity, "你好啊，$text", Toast.LENGTH_SHORT)
					makeText.show()
					//处理确定按钮了，且过 js result 传递，告诉js点击的是确定按钮(参数就是输入框新输入的值，我们需要回传到js中)
					result?.confirm(text)
				}
				setNegativeButton("取消") { _, _ ->
					//处理取消按钮，且过 js result 传递，告诉js点击的是取消按钮
					result?.cancel()
				}
				setOnCancelListener {
					//防止用户点击对话框外围，再次点击按钮页面无反应
					result?.cancel()
				}
				show()
			}
			//自己处理
			return true
		}

		override fun onJsConfirm(view: WebView?, url: String?, message: String?, result: JsResult?): Boolean {
			with(AlertDialog.Builder(this@MainActivity)) {
				setTitle(("提示:" + "Java成功重写了Js的Confirm方法"))
				setMessage(message)//这个 message 就是 alert 传递过来的值
				setPositiveButton("确定") { _, _ ->
					//处理确定按钮了，且通过 js result 传递，告诉js点击的是确定按钮
					result?.confirm()
				}
				setNegativeButton("取消") { _, _ ->
					//处理取消按钮，且通过 js result 传递，告诉js点击的是取消按钮
					result?.cancel()
				}
				setOnCancelListener {
					//防止用户点击对话框外围，再次点击按钮页面无反应
					result?.cancel()
				}
				show()
			}
			//自己处理
			return true
		}
	}

	/**
	 * 重写返回回调监听
	 * 返回上一页，而不是退出程序
	 */
	override fun onBackPressed() {
		//判断WebView是否可返回
		if (webview.canGoBack()) {
			//返回上一页
			webview.goBack()
			return
		}
		super.onBackPressed()
	}
}

